<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Video;
use App\Models\VideoCategory;

class ImportFromPpvod implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }


    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $inputs = $this->data;
        $data['shareid'] = $inputs['shareid'];
        $data['title'] = $inputs['orgfile'];
        $data['face_img'] = $inputs['rpath'].'/1';
        $data['url'] = $inputs['rpath'].'/index.m3u8';
        $data['time'] = secToTime($inputs['metadata']['time']??0);
        $data['category_id'] = 99999;
        if($inputs['category']){
            $categories = VideoCategory::select('id','name')->get();
            foreach($categories as $category){
                if(($category->name) == $inputs['category']){
                    $category_id =$category->id;
                    $data['category_id'] = $category_id;
                    break;
                }
            }
            
        }
        if($data['category_id'] == 99999){//没有的分类暂时不保存
            return;
        }
        //读取图片base64
        $picurl = $inputs['picdomain']. $inputs['rpath'].'/1.jpg';
        $pic_base64 = base64_encode(file_get_contents($picurl));
        $pic_base64 = substr( $pic_base64,4);
        // $pic_base64 .= '=/';
        $data['base64'] = $pic_base64;

;       $order = Video::updateOrCreate(
            ['url' => $data['url']],
            $data
        );
    }
}
